<template>
    <div ref="listRef" :class="['scroll-wrap', { 'scroll-wrap-horizontal' : scrollX}]">
        <div class="content">
            <slot></slot>
        </div>
    </div>
</template>

<script>
import { onMounted, onBeforeUnmount, onUpdated, ref, nextTick } from 'vue'
import BScroll from '@better-scroll/core'
export default {
    name: 'ListScroller',
    props: {
        // 水平滚动
        scrollX: {
            type: Boolean,
            default: true
        },
        // 垂直滚动
        scrollY: {
            type: Boolean,
            default: false
        }
    },
    setup(props) {
        const listRef = ref(null)
        const inst = ref(null)
        const initScroll = () => {            
            if (!listRef.value) {
                return
            }
            inst.value = new BScroll(listRef.value, {
                scrollX: props.scrollX,
                scrollY: props.scrollY,
                probeType: 3
            })
        }
        const refresh = () => {
            inst.value?.refresh()
        }

        const scrollToElement = (el, time, offsetX, offsetY) => {    
            inst.value?.scrollToElement(el, time, offsetX, offsetY)
        } 

        onMounted(() => {
            nextTick(() => {
                initScroll()
            })                  
        })
        onUpdated(() => {
            refresh()
        })
        onBeforeUnmount(() => {
            if(inst.value) {
                typeof inst.value.destroy === 'function' && inst.value.destroy()
                inst.value = null  
            }                     
        })

        return {
            listRef,
            scrollToElement
        }
    }
}
</script>

<style lang="scss" scoped>
    .scroll-wrap {
        height: 200px;
        overflow: hidden;
        &-horizontal {
            height: auto;
            white-space: nowrap;   
            .content{
                display: inline-block;
            }     
        }
    }
</style>